package cn.shiwei.shopcart.service.impl;

import cn.shiwei.basic.service.impl.BaseServiceImpl;
import cn.shiwei.basic.util.LoginContextUtil;
import cn.shiwei.basic.util.RequestStatus;
import cn.shiwei.pet.domain.Pet;
import cn.shiwei.pet.mapper.PetMapper;
import cn.shiwei.shopcart.domain.ShopCart;
import cn.shiwei.shopcart.mapper.ShopCartMapper;
import cn.shiwei.shopcart.service.IShopCartService;
import cn.shiwei.user.domain.Logininfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ShopCartServiceImpl extends BaseServiceImpl<ShopCart> implements IShopCartService {

    @Autowired
    private ShopCartMapper shopCartMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addCart(Long id) {
        Logininfo loininfo = LoginContextUtil.getLoininfo();

        // 生成一个新的ShopCart, 保存到数据库
        ShopCart shopCart = new ShopCart();
        shopCart.setLogininfoId(loininfo.getId());
        shopCart.setProductId(id);
        shopCart.setShopState(ShopCart.ADD_TO_CART);
        Pet pet = petMapper.loadById(id);
        shopCart.setTypeId(pet.getType_id());
        System.out.println(pet);
        System.out.println(shopCart);
        shopCartMapper.save(shopCart);

        // 更新redis
        flushRedis();
    }

    @Override
    public RequestStatus getCart() {

        String key = toKey();
        // 根据用户信息查询redis中的缓存
        String list = (String)redisTemplate.opsForValue().get(key);
        // 如果redis中可以查出缓存, 就返回缓存
        if (!StringUtils.hasText(list)){
            List<ShopCart> shopCarts = flushRedis();
            return RequestStatus.me().setResultObj(shopCarts);
        }
        // 如果redis中查不出缓存, 就从数据库中拿到用户的购物车信息, 存入redis并向前端返回
        System.out.println(list);
        JSONArray objects = JSONArray.parseArray(list);
        System.out.println("解析的json " + objects);
        return RequestStatus.me().setResultObj(objects);
    }

    @Override
    public void delCart(Long id) {
        // 根据传入的购物车id和删除状态修改购物车, 再刷新redis即可
        shopCartMapper.updateState(id, LoginContextUtil.getLoininfo().getId(), ShopCart.DEL_TO_CART);
        flushRedis();
    }

    @Override
    public BigDecimal calCart(List<Long> ids) {
        // 查询除ids中对应的商品(且状态为1(加入购物车状态))
        List<ShopCart> shopCarts = shopCartMapper.patchLoadByIdAndState(ids, ShopCart.ADD_TO_CART);
        BigDecimal bigDecimal = shopCarts.stream()
                // 将对象的mongey取出来map为Bigdecimal
                .map(shopCart -> shopCart.getPet().getSaleprice())
                // 使用reduce聚合函数,实现累加器(选用ten, 因为邮费10)
                .reduce(BigDecimal.TEN,BigDecimal::add);
        System.out.println("金额" + bigDecimal);
        return bigDecimal;
    }

    private  List<ShopCart> flushRedis(){
        String key = toKey();
        List<ShopCart> shopCarts = shopCartMapper.loadByLogininfoId(LoginContextUtil.getLoininfo().getId(), ShopCart.ADD_TO_CART);
        String string = JSONObject.toJSONString(shopCarts);
        System.out.println("转成的json" + string);
        // 存入redis, 30分钟
        redisTemplate.opsForValue().set(key, string.toString(), 30, TimeUnit.MINUTES);
        return shopCarts;
    }
    private String toKey(){
        Logininfo loininfo = LoginContextUtil.getLoininfo();
        // 拼接key
        return ShopCart.SHOPPING_CART_DETAILS + loininfo.getUsername();
    }
}
